package com.yeban.javase.day19.answer.test4;

import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;

/**
 * @Desc 客户端
 * @Author yeban
 * @Date 2025/11/4
 */
public class TCPClient {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        Socket socket = null;
        try {
            socket = new Socket("localhost", 8899);
            System.out.println("==========Client" + socket.getInetAddress() + "上线==========");

            new Thread(new ReadThread(socket, countDownLatch)).start();
            new Thread(new WriteThread(socket, countDownLatch)).start();
            countDownLatch.await(); // 阻塞
        } catch (ConnectException e) {
            System.out.println("服务器繁忙,请稍后重试~");
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if(socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            System.exit(0);
        }
    }
}
